﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WPF_MVVM_Simple.Commands
{
    /// <summary>
    /// 用ICommand解耦‘用户界面’与‘事件’，即控件事件不写在页面的默认.cs代码中
    /// 这是实现MVVM（Model-View-ViewModel）设计模式的关键部分
    /// </summary>
    public class RelayCommand : ICommand
    {
        #region 变量
        /// <summary>
        /// 执行操作
        /// </summary>
        private Action<object?> _Excute;
        /// <summary>
        /// 如果可以执行Execute方法，则返回true；否则返回false
        /// </summary>
        private Func<object?, bool> _CanExcute;

        /// <summary>
        /// 当CanExecute的返回值可能发生更改时,会触发该事件
        /// </summary>
        public event EventHandler? CanExecuteChanged;
        #endregion 变量

        /// <summary>
        /// 如果可以执行Execute方法，则返回true；否则返回false
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object? parameter)
        {
            return _CanExcute == null ? true : _CanExcute(parameter);
        }

        /// <summary>
        /// 执行操作
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object? parameter)
        {
            if (_Excute != null)
                _Excute(parameter);
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ExcuteMethod"></param>
        /// <param name="CanExcuteMethod"></param>
        public RelayCommand(Action<object?> ExcuteMethod, Func<object?, bool> CanExcuteMethod)
        {
            _Excute = ExcuteMethod;
            _CanExcute = CanExcuteMethod;
        }
    }
}